<template>

  <div>
    <!--  -->
    <RePage>
      <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
        <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
        <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
      </MyFormCreate>
      <div>
        <el-button :disabled="operate.checkedProject == null" v-auth="'business.mainte.create'" type="primary" :icon="Plus" @click="add">添加</el-button>
        <el-button v-auth="'business.mainte.remove'" type="danger" :icon="Delete" :disabled="!selectionData.length"
          @click="deletes()">批量删除</el-button>
        <!-- <sj-button custom-type="sred" @click="deletes"  :disabled="!selectionData.length">批量删除</sj-button> -->
      </div>
      <pure-table class="mt-5" :data="tableData.data" showOverflowTooltip border @selection-change="selectionChange"
        :columns="initPureTableConfig(roleTableConfig)" :isShowPag="false">
        <template #status="{ row }">
          <el-tag :type="row.status == 1 ? 'success' : row.status == 2 ? 'info' : 'warning'">
            {{ isNullOrEmpty(row.status == 1 ? '履约中' : row.status == 2 ? '已过期' : '已失效') }}
          </el-tag>

        </template>
        <!-- <el-table-column type="selection"></el-table-column> -->
        <template #action="{ row }">
          <el-space>
            <sj-link custom-type="sblue" :underline="false"
              @click="info(row)">查看</sj-link>
            <sj-link v-auth="'business.mainte.update'" custom-type="sblue" :underline="false"
              @click="edit(row)">编辑</sj-link>
            <!-- <sj-link custom-type="sred" :underline="false" @click="deletes(row)">删除</sj-link> -->
          </el-space>
        </template>
      </pure-table>
      <div class="mt-5">
        <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
          :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import editForm from "./form.vue";
import infos from "./info.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, getInfo, addInfo, editInfo, deleteInfo } from '@/api/operate/maintenance/contract/index';
import { titles, defaultSearchFrom, prompt, defaultInfoFrom } from './index';
import { addDialog } from "@/components/ReDialog";
import { deviceDetection, debounce, cloneDeep } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customPromiseDebounce } from "@/utils/functions";
import { usePageVariablesStoreHook } from '@/store/modules/pageVariables'
const operate = usePageVariablesStoreHook().getOperate()
const usePageVariablesStore = usePageVariablesStoreHook()
const route = useRoute()  // 获取路由参数
const selectionData = ref([]);
const searchFrom = ref(defaultSearchFrom());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0,

});
const status = ref([
  {
    value: 1,
    label: '履约中',
  },
  {
    value: 2,
    label: '已过期',
  },
  {
    value: 3,
    label: '已失效',
  }
])
const searchFormRules = [
  {
    type: 'input', field: 'mainteUnityName', title: titles.mainteUnityName, value: null,

    props: {
      placeholder: prompt.mainteUnityName, clearable: true,


    }
  },
  {
    type: 'select', field: 'status', title: titles.status, value: null,
    options: status.value, props: {
      placeholder: prompt.status, clearable: true
    }
  },
  {
    type: 'select', field: 'isWillExpired', title: titles.isWillExpired, value: null,
    options: [
      { label: '即将到期', value: 1 },
    ],
    props: {
      placeholder: prompt.isWillExpired, clearable: true
    }
  },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];

const roleTableConfig = [
  { type: "selection", align: "left" },
  { prop: 'id', label: titles.id, width: 100, fixed: 'left' },
  { prop: 'unityName', label: titles.unityName, minWidth: 150 },
  { prop: 'projectName', label: titles.projectName, minWidth: 150 },
  { prop: 'mainteName', label: titles.mainteName, minWidth: 100 },
  { prop: 'mainteUnityName', label: titles.mainteUnityName, minWidth: 150 },
  { prop: 'contractNO', label: titles.contractNO, minWidth: 100 },
  { slot: 'status', label: titles.status, minWidth: 100 },
  { prop: 'beginDate', label: titles.beginDate, minWidth: 120 },
  { prop: 'endDate', label: titles.endDate, minWidth: 150 },
  { prop: 'circle', label: titles.circle, minWidth: 100 },
  { slot: 'action', label: titles.action, width: 100, fixed: 'right' },
];
onMounted(() => {
  if (route.query.isWillExpired) {
    searchFrom.value.isWillExpired = Number(route.query.isWillExpired)
    key.value++
  }
  getTableList()
});
// 获取列表数据
const getTableList = () => {
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchFrom.value, defaultSearchFrom())
  key.value++
  getTableList()
}
// 详情
const info = (row) => {
  addDialog({
    title: `维保合同详情`,
    hideFooter: true,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(infos, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        formInline: defaultInfoFrom()
      }
      getInfo({ id: row.id }).then(res => {
        if (res.code == 200) {
          showInfo.value = res.result
          options.props.formInline = res.result
        }
      }).finally(() => {
        options.props.isLoading = false
      })
    },
  });
}
// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog()
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑维保合同", row)
}
// 删除
const deletes = (row?) => {
  console.log("ids集合", selectionData.value);
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: row ? [row.id] : selectionData.value.map(item => item.id) }).then(res => {


        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
// 开启弹窗
const openDialog = (title = "添加维保合同", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoFrom(),
          addORupdate:2
        }
        getInfo({ id: row.id }).then(res => {
          if (res.code == 200) {
            showInfo.value = res.result
            options.props.formInline = res.result
          }
        }).finally(() => {
          options.props.isLoading = false
        })
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoFrom(),
          addORupdate:1
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.circle = options.props.formInline.circle

      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加维保合同") {
            formData.projectId = usePageVariablesStore.getOperate().checkedProject



              formData.annex = formData.annexFiles.map(item => item.url)


            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            formData.projectId = row.projectId
            formData.annex = formData.annexFiles.map(item => item.url)
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();

              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
const selectionChange = data => {
  selectionData.value = data;
  console.log("删除", data);

};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>
<style lang="scss" scoped></style>
